package com.aliengen.thingple.thingple.fillingstation;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Spinner;

import com.aliengen.thingple.cmc168mwithservice.Common;
import com.aliengen.thingple.thingple.AbstractThingpleActivity;
import com.aliengen.thingple.thingple.R;
import com.aliengen.thingple.thingple.handler.CMCHandler;
import com.aliengen.thingple.thingple.tag.CylinderTag;
import com.aliengen.thingple.thingple.tag.exception.InvalidTagException;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
public class AnomalyActivity extends AbstractThingpleActivity {
    protected CylinderTag cylinder;
    protected Spinner controlPointSpinner;
    protected RadioGroup phaseRadioGroup;

    protected Button validateButton;

    protected AddAnomalyThread thread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_anomaly);
        setOperatorName();

        this.cylinder = (CylinderTag) getIntent().getExtras().get("cylinder_tag");
        setText(R.id.cylinderReference, R.string.cylinder_reference, this.cylinder.getReference());

        /**
         * Retrieve the containers.
         */
        //LinearLayout checkLayout = (LinearLayout) this.findViewById(R.id.check_layout);
        phaseRadioGroup = (RadioGroup) this.findViewById(R.id.radiogroup_anomaly_instant);

        /**
         * Add the checkboxes.
         */
        //String[] controlPoints = getResources().getStringArray(R.array.inspection_control_points);
        String[] phasesString = getResources().getStringArray(R.array.inspection_steps);
        for(int i=0; i < phasesString.length; i++)
        {
            RadioButton b = new RadioButton(this);
            b.setId(i);
            b.setText(phasesString[i]);
            phaseRadioGroup.addView(b);
        }

        controlPointSpinner = (Spinner) findViewById(R.id.inspection_anomaly);
        validateButton = (Button) findViewById(R.id.buttonValidate);

        mApplication.getHandler().setOnEventListener(new CMCHandler.OnEventListener() {
            @Override
            public void onPressDown() {
            }

            @Override
            public void onPressUp() {
            }

            @Override
            public void onReceiveData() {
            }

            @Override
            public void onRead(String data) {
            }

            @Override
            public void onReadFailed() {
            }

            @Override
            public void onWrite() {
                Log.i("AnomalyActivity", "onWrite");
                thread.start();
                mApplication.mService.device.unselect();
            }

            @Override
            public void onWriteFailed() {
                Log.i("AnomalyActivity", "onWriteFailed");
                mApplication.mService.device.unselect();
                showToast(R.string.anomaly_define_error);
                validateButton.setEnabled(true);
            }

            @Override
            public void onTagSelected() {
                byte[] epc = cylinder.getEpc();
                Log.i("AnomalyActivity", "Preceding EPC: " + Common.arrByte2String(epc, 0, epc.length));

                byte[] data = epc;
                data[5] = (byte) ((data[5] & 0xFF) | 0x01);

                try
                {
                    cylinder = new CylinderTag(data);
                    Log.i("AnomalyActivity", "New EPC: " + Common.arrByte2String(data, 0, data.length));
                    mApplication.mService.device.write(data, 4000);
                } catch(InvalidTagException e)
                {
                    e.printStackTrace();
                    Log.e("AnomalyActivity", "Tag problem!");
                    showToast("Unable to set the new EPC!");
                }
            }

            @Override
            public void onTagSelectFailed() {
                validateButton.setEnabled(true);
                showToast("Select function not working! Try to update the firmware!");
            }
        });
    }

    class AddAnomalyThread extends Thread {
        @Override
        public void run() {
            //String controlPointSelected = (String)controlPointSpinner.getSelectedItem();

            int position = controlPointSpinner.getSelectedItemPosition();
            String[] inspectionString = getResources().getStringArray(R.array.inspection_control_points_slug);
            String controlPointSelected = inspectionString[position];

            String[] phasesString = getResources().getStringArray(R.array.inspection_steps_slug);
            int selected = phaseRadioGroup.getCheckedRadioButtonId();

            String phase = "";
            if(phasesString.length > selected && selected >= 0) {
                phase = phasesString[selected];
            }

            Log.i("AddAnomalyThread", "Control point: " + controlPointSelected + ", phase: " + phase);

            if(mApplication.mService.api.addAnomaly(AnomalyActivity.this.cylinder, phase, controlPointSelected)) {
                showToast(R.string.anomaly_defined);
                AnomalyActivity.this.finish();
            }
            else
            {
                showToast(R.string.anomaly_define_error);
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    validateButton.setEnabled(true);
                }
            });
        }
    };

    public void onClickValidate(View view){
        thread = new AddAnomalyThread();
        validateButton.setEnabled(false);
        byte[] epc = this.cylinder.getEpc();
        mApplication.mService.device.setPower(28);
        mApplication.mService.device.select(epc, 2000);
    }
}
